/// Copyright (c) Microsoft Corporation.  All rights reserved.

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Diagnostics;

namespace Microsoft.VSPowerToys.Common.TaskManager
{
	public class UninstallSoftwareTask : Task
	{
		#region Private Members

		/// <summary>
		/// Location of MSI file
		/// </summary>
		private string softwareProductCode;

		private bool silentMode = true;

		private Dictionary<string, string> parameters = new Dictionary<string, string>();

		#endregion

		#region Public Properties

		/// <summary>
		/// GUID for the product to be uninstalled.
		/// </summary>
		public string SoftwareProductCode
		{
			get
			{
				return this.softwareProductCode;
			}
		}

		/// <summary>
		/// If set to true msiexec process will launch in quiet mode.
		/// </summary>
		public bool RunInSilentMode
		{
			get
			{
				return this.silentMode;
			}

			set
			{
				this.silentMode = value;
			}
		}

		/// <summary>
		/// Parameters that will be sent to msiexec process
		/// </summary>
		public Dictionary<string, string> Parameters
		{
			get
			{
				return this.parameters;
			}
		}

        public override bool IsCancellable
        {
            get
            {
                return false;
            }
        }
		#endregion

		#region Constructors

        /// <summary>
        /// Creates a new Uninstall task for the specified product
        /// </summary>
        /// <param name="productCode">GUID of product to uninstall</param>
        public UninstallSoftwareTask(string productCode)
			: base(productCode)
        {
			this.softwareProductCode = productCode;
        }
        
        #endregion

		/// <summary>
		/// Executes the uninstallation of the product.
		/// </summary>
		public override void PerformTask()
		{
			StringBuilder arguments = new StringBuilder();
			arguments.Append("/X{" + this.SoftwareProductCode + "}");
			if (this.RunInSilentMode)
			{
				arguments.Append(" /quiet /norestart");
			}
			foreach (string key in this.Parameters.Keys)
			{
				arguments.Append(" " + key + "=\"" + this.Parameters[key] + "\"");
			}

			int returnCode = 0;
			try
			{
				Process toolUninstallProcess = Process.Start("msiexec", arguments.ToString());
				toolUninstallProcess.WaitForExit();
				returnCode = toolUninstallProcess.ExitCode;
			}
			catch (System.ComponentModel.Win32Exception ex)
			{
				throw new TaskException("Unknown error occured", ex, this);
			}
			switch (returnCode)
			{
				case 0:
					return;
				default:
					throw new MsiException(this.SoftwareProductCode, returnCode, this);
			}
		}
	}
}
